package com.rds.document.controller;

import com.rds.common.annotation.Log;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.service.DocumentService;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.poi.ExcelUtil;
import com.rds.common.utils.rds.HistoryRecordUtil;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.document.domain.RdaLibrary;
import com.rds.document.service.IRdaLibraryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档库Controller
 *
 * @author rds
 * @date 2021-07-21
 */
@RestController
@RequestMapping("/pms/library")
public class RdaLibraryController extends BaseController
{
    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private IRdaLibraryService rdaLibraryService;
    /** 文档库表名 */
    private static final String tableName = "rda_library";

    /**
     * 查询文档库列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        //非超级管理员查询时加公司ID过滤数据
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            queryWrapper.add("and company_id="+SecurityUtils.getCompanyId());
        }
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        List<HashMap<String,Object>> list=dynamicService.selectDataList(tableName,queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询我的文档库列表
     */
    @GetMapping("/myLibrary")
    public TableDataInfo myLibrary(HttpServletRequest request)
    {
        startPage();
        ArrayList<String> queryWrapper=new ArrayList<>();
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> parameterMap=new HashMap<>();
        for (String key : map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
        //加当前登录用户ID过滤数据
        queryWrapper.add("and ownerid="+SecurityUtils.getUserId());
        if(parameterMap.get("searchValue")!=null && !parameterMap.get("searchValue").equals("")){
            String searchValue=" and name ~* '"+parameterMap.get("searchValue")+"' or description ~* '"+parameterMap.get("searchValue")+"'";
            queryWrapper.add(searchValue);
        }
        List<HashMap<String,Object>> list=dynamicService.selectDataList(tableName,queryWrapper);
        return getDataTable(list);
    }

    /**
     * 获取文档库详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        HashMap<String,Object> library=dynamicService.selectDataById(tableName,id);
        return AjaxResult.success(library);
    }

    /**
     * 新增文档库
     */
    @Log(title = "文档库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RdaLibrary rdaLibrary)
    {
        if(SecurityUtils.verifyPermissions("created", String.valueOf(rdaLibrary.getStateid()))){
            return error("您没有此状态的创建权限！");
        }
        Long userId = SecurityUtils.getUserId();
        rdaLibrary.setOwnerid(userId.intValue());
        rdaLibrary.setId(SnowFlakeUtils.nextId());
        rdaLibrary.setCompanyId(SecurityUtils.getCompanyId());
        return toAjax(rdaLibraryService.insertRdaLibrary(rdaLibrary));
    }

    /**
     * 修改文档库
     */
    @Log(title = "文档库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RdaLibrary rdaLibrary)
    {
        if(SecurityUtils.verifyPermissions("modify", String.valueOf(rdaLibrary.getStateid()))){
            return error("您没有此状态的修改权限！");
        }
        int num=rdaLibraryService.updateRdaLibrary(rdaLibrary);
        if(num>0){
            new HistoryRecordUtil(dynamicService).recordHistory(rdaLibrary.getId(),"修改文档库", Math.toIntExact(rdaLibrary.getStateid()),"文档库管理",rdaLibrary.getName());
        }
        return toAjax(rdaLibraryService.updateRdaLibrary(rdaLibrary));
    }

    /**
     * 删除文档库
     */
    @Log(title = "文档库", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int successNum=0;
        int verifyNum=0;
        for (Long id:ids){
            HashMap<String,Object> library=dynamicService.selectDataById(tableName,id);
            if(SecurityUtils.verifyPermissions("remove", String.valueOf(library.get("stateid")))){
                verifyNum++;
            }else{
                int num=dynamicService.deleteDataById(tableName, id);
                if(num>0){
                    successNum++;
                }
            }
        }
        return AjaxResult.getRemoveAjaxResult(successNum, verifyNum);
    }
}
